package com.polaris.live.ui.recharge

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.CollectionUtils
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.SpanUtils
import com.blankj.utilcode.util.StringUtils
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.ktx.Firebase
import com.lxj.xpopup.XPopup
import com.polaris.live.adapter.recharge.RechargeAdapter
import com.polaris.live.adapter.recharge.RechargeBannerAdapter
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.ext.dp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.constant.EventConst
import com.polaris.live.constant.TrackEventConst
import com.polaris.live.constant.UserConst
import com.polaris.live.databinding.FragmentRechargeBinding
import com.polaris.live.dialog.ChargeFailureDialog
import com.polaris.live.dialog.RechargeWhatDialog
import com.polaris.live.im.manager.ImNoticeManager
import com.polaris.live.manager.GooglePayManager
import com.polaris.live.popup.RechargeBeansToDiamondsPopup
import com.polaris.live.resp.back_resp.PayerRechargePriceListVo
import com.polaris.live.resp.back_resp.RechargeCoinPurchasePriceResp
import com.polaris.live.translation.R
import com.polaris.live.utils.TrackHelper
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.postEvent
import com.polaris.live.utils.route.RouterUtils
import com.polaris.live.utils.route.SpanClickUtils
import com.polaris.live.viewmodel.RechargeViewModel
import com.zhpan.indicator.enums.IndicatorSlideMode

/**
 * RechargeFragment
 *
 * @author Created by 半仙 on 2024/3/13/013 14:07
 */
class RechargeFragment : BaseVbFragment<RechargeViewModel, FragmentRechargeBinding>() {

    private val mAdapterFirst: RechargeAdapter by lazy {
        RechargeAdapter()
    }

    private val mAdapter: RechargeAdapter by lazy {
        RechargeAdapter()
    }

    private val mBannerAdapter: RechargeBannerAdapter by lazy {
        RechargeBannerAdapter()
    }

    private var rechargeData: RechargeCoinPurchasePriceResp? = null

    override fun initView(savedInstanceState: Bundle?) {
        Firebase.analytics.postEvent(EventConst.ENTER_DIAMOND)

        init()
        initObserve()
        initListener()

        mBinding.bannerView.apply {
            registerLifecycleObserver(lifecycle)
            setAdapter(mBannerAdapter)
            setIndicatorSlideMode(IndicatorSlideMode.NORMAL)
            setIndicatorVisibility(View.GONE)
            setRoundCorner(10.dp)
            setScrollDuration(500)
        }

        mBinding.userCoin.text = "${UserManager.getUser().account?.userCoins ?: 0}" + " "

        TrackHelper.postTrack(
            this,
            TrackEventConst.EVENT_BUY_DIAMONDS_PAGE_PV,
            TrackEventConst.TRACK_PAGE,
            TrackHelper.rechargeForMap()
        )
        mBinding.rechargeAc.registerObserve(lifecycle, mViewModel)
    }

    private fun initListener() {
        mBinding.rechargeWhat.setOnSingleClickListener {
            XPopup.Builder(requireContext())
                .isDestroyOnDismiss(true)
                .asCustom(RechargeWhatDialog(requireContext()))
                .show()
        }
        mAdapterFirst.setOnItemClickListener { _, _, position ->
            buyShow(mAdapterFirst.getItem(position))
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            buyShow(mAdapter.getItem(position))
        }
        mBinding.tvEmail.setOnSingleClickListener {
            RouterUtils.routerWeb(
                ImageUtils.imgPath(AppConst.Customer.suffix),
                mapOf("type" to "${CommonConst.FAQType.RECHARGE}")
            )
        }
        mBinding.exchangeBeansDiamondsRl.setOnSingleClickListener {
            rechargeData?.let {
                RechargeBeansToDiamondsPopup.show(requireContext(), mViewModel, it)
            }
        }
    }

    private fun buyShow(item: PayerRechargePriceListVo) {
        TrackHelper.postTrack(
            this,
            TrackEventConst.EVENT_TOPUP_PC,
            params = TrackHelper.rechargeForMap(mutableMapOf("price" to item.price))
        )
        GooglePayManager.buyShow(requireActivity(),
            item.priceId,
            UserConst.From.UNKNOWN,
            item.payerRechargeRewardsType,
            price = item.price,
            showToast = false,
            onSuccess = {
                mViewModel.getRechargeList()
            },
            onFailure = {
                if (it?.errCode == CommonConst.ErrorCode.PAY_FAILURE_FLUSHED) {
                    mViewModel.getRechargeList()
                }

                XPopup.Builder(requireContext())
                    .isDestroyOnDismiss(true)
                    .asCustom(
                        ChargeFailureDialog(requireContext())
                    ).show()

                it?.errorMsg?.let {
                    ToastGravity.showGravity(it)
                }
            })
    }

    @SuppressLint("SetTextI18n")
    private fun initObserve() {
        mViewModel.rechargeLiveData.observe(this) { resultState ->
            parseState(resultState, {
                if (CollectionUtils.isEmpty(it.rewardsPriceListVo)) {
                    mBinding.rechargeLlFirst.visibility = View.GONE
                } else {
                    mBinding.rechargeLlFirst.visibility = View.VISIBLE

                    mAdapterFirst.setList(it.rewardsPriceListVo)
                }

                if (CollectionUtils.isEmpty(it.rechargePriceListVo)) {
                    mBinding.rechargeLl.visibility = View.GONE
                } else {
                    mAdapter.setList(it.rechargePriceListVo)
                }

                if (!CollectionUtils.isEmpty(it.rewardsPriceListVo)) {
                    for (payerRechargePriceListVo in it.rewardsPriceListVo) {
                        if (payerRechargePriceListVo.rewardsExp != 0L) {
                            mViewModel.startTimeCount(payerRechargePriceListVo.rewardsExp)
                            break
                        }
                    }
                } else {
                    for (payerRechargePriceListVo in it.rechargePriceListVo) {
                        if (payerRechargePriceListVo.rewardsExp != 0L) {
                            mViewModel.startTimeCount(payerRechargePriceListVo.rewardsExp)
                            break
                        }
                    }
                }

            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
        mViewModel.bannerLiveData.observe(this) { resultState ->
            parseState(resultState, {
                if (it.isEmpty()) {
                    mBinding.consLayout.visibility = View.GONE
                } else {
                    mBinding.consLayout.visibility = View.VISIBLE
                }
                mBinding.bannerView.create(it)
            })
        }
        mViewModel.timeChange.observe(this) { time ->
            mAdapter.data.forEach {
                if (it.rewardsExp != 0L) {
                    it.rewardsExp = time
                }
            }
            mAdapterFirst.data.forEach {
                if (it.rewardsExp != 0L) {
                    it.rewardsExp = time
                }
            }
            mAdapter.notifyItemRangeChanged(0, mAdapter.data.size)
            mAdapterFirst.notifyItemRangeChanged(0, mAdapterFirst.data.size)
        }
        mViewModel.purchasePriceLiveData.observe(this) { resultState ->
            parseState(resultState, {
                if (it.priceList.isEmpty()) {
                    mBinding.exchangeBeansDiamondsRl.visibility = View.GONE
                } else {
                    mBinding.exchangeBeansDiamondsRl.visibility = View.VISIBLE
                    rechargeData = it
                }
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
        ImNoticeManager.observeAccountChange(this) {
            mBinding.userCoin.text = "${UserManager.getUser().account?.userCoins ?: 0}" + " "
        }
    }

    private fun init() {
        mBinding.firstRecycler.apply {
            adapter = mAdapterFirst
            layoutManager = LinearLayoutManager(context)
            itemAnimator = null
        }

        mBinding.recycler.apply {
            adapter = mAdapter
            itemAnimator = null
            layoutManager = LinearLayoutManager(context)
        }

        if ((UserManager.getUser().account?.gainCoins ?: 0) >= 100000) {
            mViewModel.purchasePrice()
        }
        mBinding.tvEmail.text = SpanUtils.with(mBinding.tvEmail)
            .append(StringUtils.getString(R.string.recharge_encountering))
            .setUnderline()
            .create()

        val span = SpanClickUtils.with(mBinding.rechargeBottomText)
            .append("${resources.getText(R.string.recharge_terms_of_service)}").setUnderline()
            .setClickSpan(object : ClickableSpan() {
                override fun updateDrawState(paint: TextPaint) {
                    paint.isUnderlineText = true
                    paint.bgColor = Color.TRANSPARENT
                }

                override fun onClick(widget: View) {
                    RouterUtils.routerGoto(CommonConst.Agreement.TERMS_OF_SERVICE)
                }
            })
            .setForegroundColor(Color.parseColor("#FFFFFF"))
            .append(" ${resources.getText(R.string.and)} ")
            .setForegroundColor(ColorUtils.getColor(com.polaris.live.R.color.fff_70))
            .append("${resources.getText(R.string.recharge_privacy_policy)}").setUnderline()
            .setClickSpan(object : ClickableSpan() {
                override fun updateDrawState(paint: TextPaint) {
                    paint.isUnderlineText = true
                    paint.bgColor = Color.TRANSPARENT
                }

                override fun onClick(widget: View) {
                    RouterUtils.routerGoto(CommonConst.Agreement.PRIVACY_POLICY)
                }
            })
            .setForegroundColor(ColorUtils.getColor(com.polaris.live.R.color.white))
            .create()

        mBinding.rechargeBottomText.text = span

        mViewModel.getRechargeList()

        mViewModel.getBannerList()
    }

}